import React, { useEffect } from "react";
import { useState ,useCallback, useMemo} from "react"
 
import styled from "./index.module.less"

import { Icon , Badge ,Button , TextField,Autocomplete,  } from "@shopify/polaris"

import { DragHandleMinor ,DeleteMajor  ,SearchMinor} from "@shopify/polaris-icons"
 
function Item({ children, index, onMove, listLength, need , title,handleAction , connected}) {
  const [needs,setNeeds] = useState(need)
  
  const [top, setTop] = React.useState(0);
  const [isDragging, setIsDragging] = React.useState(false);
  const [zIndex, setZIndex] = React.useState(0);

  const ref = React.useRef();
  const indexRef = React.useRef(index);
  const onMoveRef = React.useRef(onMove);
  const listLengthRef = React.useRef(listLength);
  const prevRectRef = React.useRef(null);
  const animationRef = React.useRef(null);

  React.useEffect(() => {
    // 始终保持最新状态 Ref 引用
    indexRef.current = index;
    onMoveRef.current = onMove;
    listLengthRef.current = listLength;
  }, [index, onMove, listLength]);

  React.useEffect(() => {
    const el = ref.current;

    // 存储起始鼠标位置
    let startY = 0;

    let delayedSetZIndexTimeoutId;

    const mouseMove = (ev) => {
      ev.preventDefault();

      // 获取元素 Rect 并更新 Ref
      const rect = el.getBoundingClientRect();
      prevRectRef.current = rect;

      // 计算最新 Top 位置
      let latestTop = ev.clientY - startY;

      // 检查是否需要更新元素位置
      if (
        latestTop > rect.height &&
        indexRef.current < listLengthRef.current - 1
      ) {
        // move down
        // 通知父组件修改列表
        onMoveRef.current(indexRef.current, indexRef.current + 1);
        // 因为 DOM 位置被改变了，需要同步计算最新位置
        // 可以理解为计算出来的值就是元素发生交换后，松开鼠标再按住鼠标时相关变量的值。
        // 可以试着注释掉这行看看会发生什么，就能理解了（会闪一下）
        latestTop -= rect.height;
        // 开始位置也要更新
        startY += rect.height;
      } else if (latestTop < -rect.height && indexRef.current > 0) {
        // move up
        onMoveRef.current(indexRef.current, indexRef.current - 1);
        latestTop += rect.height;
        startY -= rect.height;
      }
      setTop(latestTop);
    };

    const mouseUp = (ev) => {
      ev.preventDefault();
      document.removeEventListener("mousemove", mouseMove);
      // 重置 Top
      setTop(0);
      // 结束拖拽
      setIsDragging(false);
      delayedSetZIndexTimeoutId = setTimeout(() => {
        // 延迟设置 zIndex，不然一结束拖拽该元素就会被盖到其他元素下面
        setZIndex(0);
      }, 200);
    };

    const mouseDown = (ev) => {
      ev.preventDefault();
      clearTimeout(delayedSetZIndexTimeoutId);
      // 注册事件
      document.addEventListener("mousemove", mouseMove);
      document.addEventListener("mouseup", mouseUp, { once: true });
      // 开始拖拽
      setIsDragging(true);
      setZIndex(999);
      // 记录开始位置
      startY = ev.clientY;
    };
    el.addEventListener("mousedown", mouseDown);
  }, []);

  React.useLayoutEffect(() => {
    // FLIP animation
    // https://aerotwist.com/blog/flip-your-animations/
    const el = ref.current;
    if (isDragging) {
      // 拖拽中的元素不计算
      return;
    }

    if (prevRectRef.current === null) {
      // 元素第一次渲染
      prevRectRef.current = el.getBoundingClientRect();
      return;
    }

    // 如果有动画正在运行则取消，防止拖动速度过快有鬼畜效果
    if (animationRef.current) {
      const animation = animationRef.current;
      if (animation.playState === "running") {
        // Cancel previous animation
        animation.cancel();
      }
    }

    // FLIP: First
    const prevRect = prevRectRef.current;

    // FLIP: Last
    const latestRect = el.getBoundingClientRect();
    const deltaY = latestRect.y - prevRect.y;

    prevRectRef.current = latestRect;

    if (deltaY === 0) {
      return;
    }

    // FLIP: Invert and Play
    animationRef.current = el.animate(
      [
        {
          top: `${-deltaY}px`
        },
        {
          top: `0px`
        }
      ],
      200
    );
  }, [index, isDragging]);

  //text filter
  const [show, setShow] = useState(false);

  const [value1, setValue1] = useState('');
  const handleChange1 = useCallback(
    (newValue) => setValue1(newValue),
    [],
  );
  const [value11, setValue11] = useState('');
  const handleChange11 = useCallback(
    (newValue) => setValue11(newValue),
    [],
  );
  const [value12, setValue12] = useState('');
  const handleChange12 = useCallback(
    (newValue) => setValue12(newValue),
    [],
  );
  const [value13, setValue13] = useState('');
  const handleChange13 = useCallback(
    (newValue) => setValue13(newValue),
    [],
  );
  const [value14, setValue14] = useState('');
  const handleChange14 = useCallback(
    (newValue) => setValue14(newValue),
    [],
  );
  const [value15, setValue15] = useState('');
  const handleChange15 = (newValue) => {
      setValue15(newValue)
      if(newValue){
        console.log(6666);
        setNeeds([...need,newValue])
      }
    }
  
  const [value16, setValue16] = useState('');
  const handleChange16 = useCallback(
    (newValue) => setValue16(newValue),
    [],
  );

  //XUANZHE
  const deselectedOptions = useMemo(
    () => [
      {value: 'size', label: '尺寸'},
      {value: 'color', label: '颜色'},
      {value: 'style', label: '样式'},
      {value: 'CL', label: '材料'},
    ],
    [],
  );
  const [selectedOptions, setSelectedOptions] = useState([]);
  const [inputValue, setInputValue] = useState('');
  const [options, setOptions] = useState(deselectedOptions);

  const updateText = useCallback(
    (value) => {
      setInputValue(value);

      if (value === '') {
        setOptions(deselectedOptions);
        return;
      }

      const filterRegex = new RegExp(value, 'i');
      const resultOptions = deselectedOptions.filter((option) =>
        option.label.match(filterRegex),
      );
      setOptions(resultOptions);
    },
    [deselectedOptions],
  );

  const updateSelection = useCallback(
    (selected) => {
      const selectedValue = selected.map((selectedItem) => {
        const matchedOption = options.find((option) => {
          return option.value.match(selectedItem);
        });
        return matchedOption && matchedOption.label;
      });

      setSelectedOptions(selected);
      setInputValue(selectedValue[0] || '');
    },
    [options],
  );

  const textField = (
    <Autocomplete.TextField
      onChange={updateText}
      label=""
      value={inputValue}
      // prefix={<Icon source={SearchMinor} color="base" />}
      placeholder=""
      autoComplete="off"
    />
  );

  useEffect(()=>{
    setInputValue(title)
    needs.forEach((item,index)=>{
      if(index==0){
        setValue11(item)
      }else if(index==1){
        setValue12(item)
      }else if(index==2){
        setValue13(item)
      }else{
        setValue14(item)
      }
    })
    
    
  },[])
  return (
    <>
      <div
        style={{
          // border: "1px solid black",
          padding: "10px",
          background: "white",
          transform: isDragging ? `scale(1.01)` : `scale(1)`,
          top: `${top}px`,
          transition: "transform .2s, box-shadow .2s",
          position: "relative",
          width: "100%",
          boxShadow: isDragging
            ? "0 0 10px 2px rgba(0, 0, 0, 0.5)"
            : "0 0 0 0px rgba(0, 0, 0, 0.5)",
          zIndex: zIndex.toString()
        }}
      >
        {!connected && <div className={styled.REF}>
          <div ref={ref} className={styled.Rleft}><Icon source={DragHandleMinor}></Icon></div>
          <div className={styled.Rright}>{children}</div>
        </div>}
        {connected&&<div className={styled.REF1}>
          <div className={styled.title}>选项名称</div>
          <div className={styled.TEXTF}>
            <div  className={styled.Rleft}><Icon source={DragHandleMinor}></Icon></div>
              <div className={styled.content}>
                  <Autocomplete
                    options={options}
                    selected={selectedOptions}
                    onSelect={updateSelection}
                    textField={textField}
                  />
              </div>
            <div className={styled.Icons}><Icon source={DeleteMajor}></Icon></div>
          </div>
          
        </div>}
      </div>
      {connected&&<div>
        <div className={styled.REFW}>
          <div className={styled.title1}>选项值</div>
          {need.map((item,index) => {
            
          return (
            <div key={index}>
              {index<2&&<div key={index} className={styled.TEXTF1}>
                <div  className={styled.Rleft}><Icon source={DragHandleMinor}></Icon></div>
                  <div className={styled.content}>
                    <TextField
                      label=""
                      value={index==0?value11:value12}
                      onChange={index==0?handleChange11:handleChange12}
                      autoComplete="off"
                      />
                  </div>
                <div className={styled.Icons}><Icon source={DeleteMajor}></Icon></div>
              </div>}
              {index>1&&<div key={index} className={styled.TEXTF1}>
                <div  className={styled.Rleft}><Icon source={DragHandleMinor}></Icon></div>
                  <div className={styled.content}>
                    <TextField
                      label=""
                      value={index==2?value13:value14}
                      onChange={index==0?handleChange13:handleChange14}
                      autoComplete="off"
                      />
                  </div>
                <div className={styled.Icons}><Icon source={DeleteMajor}></Icon></div>
              </div>}
            </div>
          )
        })}
        <div  className={styled.TEXTF1}>
            <div  className={styled.Rleft}><Icon source={DragHandleMinor}></Icon></div>
            <div className={styled.content}>
              <TextField
                label=""
                value={value15}
                onChange={handleChange15}
                autoComplete="off"
                />
            </div>
            <div className={styled.Icons}><Icon source={DeleteMajor}></Icon></div>
        </div>
        {needs.length==need.length?"":needs.slice(-1).map((item,index)=>{
          return (<div key={item}  className={styled.TEXTF1}>
            <div  className={styled.Rleft}><Icon source={DragHandleMinor}></Icon></div>
            <div className={styled.content}>
              <TextField
                label=""
                value={value16}
                onChange={handleChange16}
                autoComplete="off"
                />
            </div>
            <div className={styled.Icons}><Icon source={DeleteMajor}></Icon></div>
        </div>)
        })}

        <div className={styled.btn}>
          <Button size="slim" onClick={handleAction}>完成</Button>
        </div>
        </div>
        <div ref={ref} className={styled.FOOTER}></div>
      </div>}
    </>
  );
}

export default function Sortable({ list, setList }) {

  
  //展开
  const [connected1, setConnected1] = useState(false);
  const [connected2, setConnected2] = useState(false);
  const [connected3, setConnected3] = useState(true);

  const handleAction = (value) => {
    if(value==1){
      setConnected1((connected1) => !connected1);
    }else if(value==2){
      setConnected2((connected2) => !connected2);
    }else{
      setConnected3((connected3) => !connected3);
    }
  }


  return (
    <div>
      {list.map((child, i) => 
        // <Item
        //   key={child.key}
        //   index={i}
        //   listLength={list.length}
        //   onMove={(prevIndex, nextIndex) => {
        //     // 更新列表
        //     const newList = [...list];
        //     newList.splice(nextIndex, 0, newList.splice(prevIndex, 1)[0]);
        //     setList(newList);
        //     }}
        //   need={child.children.need}
        //   handleAction={()=>handleAction(i+1)}
        //   connected={i==0? connected1: connected2}
        //   title={child.children.title}
        //   >
        //   {/* {child.children} */}
        //   <div  className={styled.shuxing}>
        //   <div className={styled.CCCL}>
        //     <div className={styled.MIDDLE}>
        //       <div className={styled.Icons}>{child.children.title}</div>
        //       <div className={styled.Badges}>
        //         {child.children.need.map((items, i) => {
        //           return (
        //             <div key={i} className={styled.Badge}>
        //               <Badge>{items}</Badge>
        //             </div>
        //           );
        //         })}
        //       </div>
        //     </div>
        //   </div>
        //   <div
        //     style={{
        //       width: "36px",
        //       height: "44px",
        //       fontSize: "12px",
        //     }}
        //   >
        //     <Button
        //       size="slim"
        //       outline
        //       fullWidth
        //       onClick={() => {
        //         handleAction(i+1)
        //       }}
        //     >
        //       编辑
        //     </Button>
        //   </div>
        //   </div>
          
        // </Item>
        {
            if(i<2){
          return (<Item
            key={child.key}
            index={i}
            listLength={list.length}
            onMove={(prevIndex, nextIndex) => {
              // 更新列表
              const newList = [...list];
              newList.splice(nextIndex, 0, newList.splice(prevIndex, 1)[0]);
              setList(newList);
              }}
            need={child.children.need}
            handleAction={()=>handleAction(i+1)}
            connected={i==0? connected1: connected2}
            title={child.children.title}
            >
            {/* {child.children} */}
            <div  className={styled.shuxing}>
            <div className={styled.CCCL}>
              <div className={styled.MIDDLE}>
                <div className={styled.Icons}>{child.children.title}</div>
                <div className={styled.Badges}>
                  {child.children.need.map((items, i) => {
                    return (
                      <div key={i} className={styled.Badge}>
                        <Badge>{items}</Badge>
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>
            <div
              style={{
                width: "36px",
                height: "44px",
                fontSize: "12px",
              }}
            >
              <Button
                size="slim"
                outline
                fullWidth
                onClick={() => {
                  handleAction(i+1)
                }}
              >
                编辑
              </Button>
            </div>
            </div>
          </Item>)
         }else{
          return (<Item
            key={child.key}
            index={i}
            listLength={list.length}
            onMove={(prevIndex, nextIndex) => {
              // 更新列表
              const newList = [...list];
              newList.splice(nextIndex, 0, newList.splice(prevIndex, 1)[0]);
              setList(newList);
              }}
            need={child.children.need}
            handleAction={()=>handleAction(i+1)}
            connected={connected3}
            title={child.children.title}
            >
            {/* {child.children} */}
            <div  className={styled.shuxing}>
            <div className={styled.CCCL}>
              <div className={styled.MIDDLE}>
                <div className={styled.Icons}>{child.children.title}</div>
                <div className={styled.Badges}>
                  {child.children.need.map((items, i) => {
                    return (
                      <div key={i} className={styled.Badge}>
                        <Badge>{items}</Badge>
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>
            <div
              style={{
                width: "36px",
                height: "44px",
                fontSize: "12px",
              }}
            >
              <Button
                size="slim"
                outline
                fullWidth
                onClick={() => {
                  handleAction(i+1)
                }}
              >
                编辑
              </Button>
            </div>
            </div>
          </Item>)
         }
        }
      )}
    </div>
  );
}
